const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  try {
    console.log('开始初始化行业数据...')

    // 定义三个行业数据
    const industries = [
      {
        _id: "auto_service",
        name: "汽车服务",
        icon: "🚗",
        services: [
          {name: "机油保养", icon: "🔧"},
          {name: "美容洗车", icon: "✨"},
          {name: "维修检测", icon: "🔍"},
          {name: "轮胎服务", icon: "⚙️"},
          {name: "钣金喷漆", icon: "🎨"},
          {name: "内饰清洁", icon: "🧽"}
        ],
        status: "active",
        sort: 1
      },
      {
        _id: "hair_salon",
        name: "理发店",
        icon: "💇",
        services: [
          {name: "剪发", icon: "✂️"},
          {name: "烫发", icon: "🌀"},
          {name: "染发", icon: "🎨"},
          {name: "护理", icon: "💆"},
          {name: "造型设计", icon: "✨"},
          {name: "儿童理发", icon: "👶"}
        ],
        status: "active",
        sort: 2
      },
      {
        _id: "restaurant",
        name: "餐厅",
        icon: "🍽️",
        services: [
          {name: "小包厢(4-6人)", icon: "🚪", capacity: 6},
          {name: "中包厢(8-10人)", icon: "🚪", capacity: 10},
          {name: "大包厢(12-15人)", icon: "🚪", capacity: 15},
          {name: "豪华包厢(20人以上)", icon: "🏛️", capacity: 20}
        ],
        status: "active",
        sort: 3
      }
    ]

    // 先删除旧数据
    const deleteResult = await db.collection('industries')
      .where({_id: db.command.in(['auto_service', 'hair_salon', 'restaurant'])})
      .remove()
    
    console.log('删除旧数据结果:', deleteResult)

    // 批量添加新数据
    const addTasks = industries.map(item => {
      return db.collection('industries').add({data: item})
    })

    const results = await Promise.all(addTasks)
    
    console.log('添加结果:', results)

    return {
      success: true,
      message: `成功初始化 ${industries.length} 个行业`,
      deleteCount: deleteResult.removed,
      addCount: results.length
    }
  } catch (err) {
    console.error('初始化失败:', err)
    return {
      success: false,
      error: err.message
    }
  }
}
